package com.basic.library.view

import android.app.Activity
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.*
import android.widget.PopupWindow
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.basic.library.R


/**
 * @author yj
 * @description
 */
class MPopWin {

    private var pop: PopupWindow? = null
    var activity: Activity? = null
    var binding: ViewDataBinding? = null

    fun <T> create(
        context: Activity, resId: Int, mVariableId: Int, data: T,
        width: Int = ViewGroup.LayoutParams.WRAP_CONTENT,
        height: Int = ViewGroup.LayoutParams.WRAP_CONTENT
    ): MPopWin {
        activity = context
        if (pop == null) {
            binding = DataBindingUtil.inflate(LayoutInflater.from(context), resId, null, false)
            pop = PopupWindow(binding?.root, width, height)
            binding?.setVariable(mVariableId, data)
            pop?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            pop?.isOutsideTouchable = true
            pop?.isFocusable = true
//            pop?.isTouchable = false
        }
        pop?.setOnDismissListener {
            bg(1f)
        }
        return this
    }

    fun show(v: View?, xoff: Int = 0, yoff: Int = 10, alpha: Float = 0.8f) {
        pop?.run {
            if (isShowing) {
                dismiss()
            } else {
                v?.let {
                    showAsDropDown(it, xoff, yoff)
                    bg(alpha)
                }
            }
        }
    }

    fun showAtLocation(
        v: View?,
        gravity: Int = Gravity.BOTTOM,
        xoff: Int = 0,
        yoff: Int = 0,
        alpha: Float = 0.8f
    ) {
        pop?.run {
            if (isShowing) {
                dismiss()
            } else {
                if (Gravity.BOTTOM == gravity) {
                    pop?.animationStyle = R.style.BottomDialog
                }
                v?.let {
                    showAtLocation(it, gravity, xoff, yoff)
                    bg(alpha)
                }
            }
        }
    }

    fun bg(alpha: Float) {
        activity?.window?.run {
            val lp = attributes
            lp.alpha = alpha //设置透明度
            addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
            attributes = lp
        }
    }

    fun dismiss() {
        pop?.dismiss()
    }
}